package com.example.base.Utils;


import android.os.Handler;
import android.os.Looper;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttp;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpUtil {
  private static OkHttpUtil sOkHttpManager;

  /**
   * okhttpclient实例
   */
  private OkHttpClient mClient;

  /**
   * 因为我们请求数据一般都是子线程中请求，在这里我们使用了handler
   */
  private Handler mHandler;

  private OkHttpUtil() {
    mClient = new OkHttpClient();
    OkHttpClient.Builder builder = mClient.newBuilder();
    mClient = builder.build();

    /**
     * 初始化handler
     */
    mHandler = new Handler(Looper.getMainLooper());
  }

  /**
   * 单例模式  获取OkHttp实例
   *
   * @return
   */
  public static OkHttpUtil getInstance() {

    if (sOkHttpManager == null) {
      sOkHttpManager = new OkHttpUtil();
    }
    return sOkHttpManager;
  }

  public static void getAsync(String url, DataCallBack callBack) {
    getInstance().inner_getAsync(url, callBack);
  }

  /**
   * 内部逻辑请求的方法
   *
   * @param url
   * @param callBack
   * @return
   */
  private void inner_getAsync(String url, final DataCallBack callBack) {
    final Request request = new Request.Builder().url(url).build();

    mClient.newCall(request).enqueue(new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {
        deliverDataFailure(request, e, callBack);
      }

      @Override
      public void onResponse(Call call, Response response) throws IOException {
        String result = null;
        try {
          result = response.body().string();
        } catch (IOException e) {
          deliverDataFailure(request, e, callBack);
        }
        deliverDataSuccess(result, callBack);
      }
    });
  }


  /**
   * 分发失败的时候调用
   *
   * @param request
   * @param e
   * @param callBack
   */
  private void deliverDataFailure(final Request request, final IOException e, final DataCallBack callBack) {
    /**
     * 在这里使用异步处理
     */
    mHandler.post(new Runnable() {
      @Override
      public void run() {
        if (callBack != null) {
          callBack.requestFailure(request, e);
        }
      }
    });
  }

  /**
   * 分发成功的时候调用
   *
   * @param result
   * @param callBack
   */
  private void deliverDataSuccess(String result, final DataCallBack callBack) {
    /**
     * 在这里使用异步线程处理
     */
    mHandler.post(new Runnable() {
      @Override
      public void run() {
        if (callBack != null) {
          try {
            callBack.requestSuccess(result);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    });
  }

  /**
   * 数据回调接口
   */
  public interface DataCallBack {
    void requestFailure(Request request, IOException e);

    void requestSuccess(String result) throws Exception;
  }

}
